<script setup lang="ts">
import { ref } from 'vue';
import { showToast } from 'vant';
import image from '../assets/img.png'
import request from "@/api";
import { showSuccessToast, showFailToast } from 'vant';
const router = useRouter();
import {userStore} from "@/store/userStore.ts";
import {useRouter} from "vue-router";


const userAccount = ref('');
const userPassword = ref('');

const onSubmit = (values: any) => {
  console.log("fefefe",values)
  request.post('/user/login', {
    userAccount:userAccount.value,
    userPassword:userPassword.value
  }).then( async  (res)=>{
    const result = res.data.data
    if(result){
       await userStore().setInfo();
      console.log("shuain",userStore().userinfo)
      showToast({
        message: `欢迎${result.userAccount}`,
        icon: 'fire-o',
      });
      const redirect =sessionStorage.getItem("redirect")

      if(redirect){
        router.push({
          path: redirect,
          replace: true
        })
      }
      router.push({
        path: '/home',
        replace: true
      })
    }
    else{
      showFailToast('用户名或密码错误');
    }
}).catch((err)=>{})
  // 处理登录逻辑
};

const register = () => {
  router.push('/register')
}

const pattern = /^(?=.*[\u4e00-\u9fa5a-zA-Z0-9])[a-zA-Z0-9\u4e00-\u9fa5]{4,}$/
</script>

<template>
  <div class="login-container">
    <div class="header">
      <van-image
          round
          width="3.3rem"
          height="3.3rem"
          :src="image"
      />
      <div class="title">民大交友组队系统</div>
    </div>
    <van-form @submit="onSubmit" label-width="7em">
      <van-cell-group inset>
        <van-field size="large"
            v-model="userAccount"
            name="userAccount"
            label="用户名"
            placeholder="用户名"
            :rules="[{ pattern, message: '用户名必须大于4位' }]"
        />
        <van-field  size="large"
            v-model="userPassword"
            type="password"
            name="userPassword"
            label="密码"
            placeholder="密码"
            :rules="[{ pattern, message: '密码必须大于4位' }]"
        />
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button type="primary" class="large-button" style="margin-right: 16%; margin-left: 10%;" native-type="submit">登录</van-button>
        <van-button plain type="primary" class="large-button" @click="register">注册</van-button>
      </div>

    </van-form>

  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh; /* 使容器高度占满整个视口 */
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-right: 40px/* 图标和表单之间的间距 */
}

.header .van-image {
  margin-right: 10px; /* 图标和标题之间的间距 */
}

.title {
  font-size:2rem;
  font-weight: bold;
}
.large-button {
  width: 100px; /* 设置按钮的宽度 */
  height: 40px; /* 设置按钮的高度 */
  font-size: 16px; /* 设置按钮的文字大小 */
}
</style>
